from django.contrib.auth.decorators import login_required
from django.http import JsonResponse
from django.shortcuts import render, get_object_or_404
from django.views.decorators.csrf import csrf_exempt

from main.models import Anime
from history.models import AnimeHistory
from django.utils import timezone
import json


# Create your views here.

@login_required
def anime_history(request):
    history = AnimeHistory.objects.filter(user=request.user).order_by('-watched_at')[:10]

    return render(request, 'history/anime_history.html', context={'history': history})


def watch_anime(request):
    if request.method == 'POST':
        anime_id = request.POST.get("anime_id")
        print(anime_id)

        # anime = Anime.objects.get(id=anime_id)
        anime = get_object_or_404(Anime, id=anime_id)
        print(anime)

        # 更新观看历史
        AnimeHistory.objects.update_or_create(
            user=request.user,
            anime=anime,
            defaults={'watched_at': timezone.now()}
        )

        # 保留最近十条记录
        history_records = AnimeHistory.objects.filter(user=request.user).order_by('-watched_at')[10:]

        # 获取要删除的记录的 ID
        ids_to_delete = history_records.values_list('id', flat=True)

        if ids_to_delete:
            AnimeHistory.objects.filter(id__in=ids_to_delete).delete()

        return JsonResponse({
            "code": 1,
            'message': '观看历史已记录'
        })
    else:
        return JsonResponse({
            "code": -1,
            "msg": "'无效请求",
        })